// 使用MySQL数据库编写的index.html页面的路由，在本项目中登录注册使用MySQL，主页使用mongodb数据库，这个仅供参考

// 导入express模块
const express = require("express");
const bodyParser = require("body-parser");
const dbTool = require('./libs/dbTool')

// 创建服务器
const app = express();

// 注册中间件
app.use(bodyParser.urlencoded({ extended: false }));

// 静态资源托管
app.use(express.static("views"));

// 查询数据
app.get("/list",(req, res)=>{
    // 获取get请求参数
    console.log(req.query);
    let sql = '';
    if(req.query.userId){
        sql = `SELECT * FROM user_table where userId = '${req.query.userId}' OR userName= '${req.query.userId}' OR userPhone= '${req.query.userId}'`;
    }else{
        sql = "select * from user_table";
    }
    dbTool.mysql(sql, results=>{
       res.send(results);
    });
});

// 删除数据
app.get("/delete", (req, res)=>{
    // 获取get请求参数
    // console.log(req.query);

    const sql = `delete from user_table where userId=${req.query.userId}`;

    dbTool.mysql(sql, () => {
        res.send({
            msg : '数据删除成功',
            status : 1
        });
     });
});

// 添加数据
app.post("/add", (req, res)=>{
    // 获取post请求参数
    // console.log(req.body);

    const sql = `insert into user_table(userName,userSex,userAge,userBirth,userPhone,userAddress,userDescript,userdelete) values ('${req.body.userName}','${req.body.userSex}',${req.body.userAge},'${req.body.userBirth}','${req.body.userPhone}','${req.body.userAddress}','${req.body.userDescript}',false)`;

    dbTool.mysql(sql, () => {
        res.send({
            msg : '数据添加成功',
            status : 1
        });
    });
});

// 修改数据
app.post("/update", (req, res)=>{
    // 获取post请求参数
    // console.log(req.body);

    const sql = `update user_table set userName='${req.body.userName}',userSex='${req.body.userSex}',userAge=${req.body.userAge},userBirth='${req.body.userBirth}',userPhone='${req.body.userPhone}',userAddress='${req.body.userAddress}',userDescript='${req.body.userDescript}' where userId=${req.body.userId}`;

    dbTool.mysql(sql, () => {
        res.send({
            msg : '数据修改成功',
            status : 1
        });
    });
});


// 开启监听
app.listen(43999);